package com.ktgj.customer.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.exception.LoginException;
import com.ktgj.common.core.utils.SnowflakeUtils;
import com.ktgj.common.log.annotation.SignatureValidation;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.back.CommonTravelersBack;
import com.ktgj.customer.domain.back.PassengerDocumentsBack;
import com.ktgj.customer.domain.vo.*;
import com.ktgj.customer.domain.vo.CommonTravelersVo;
import com.ktgj.customer.service.*;
import com.ktgj.customer.vo.NationVo;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.apache.ibatis.logging.LogException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ktgj.common.log.annotation.Log;
import com.ktgj.common.log.enums.BusinessType;
import com.ktgj.common.security.annotation.PreAuthorize;
import com.ktgj.common.core.web.controller.BaseController;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.common.core.utils.poi.ExcelUtil;
import com.ktgj.common.core.web.page.TableDataInfo;

/**
 * 常用旅客信息Controller
 * 
 * @author ruoyi
 * @date 2021-09-01
 */
@ControllerAdvice
@RestController
@RequestMapping("/travelers")
public class CommonTravelersController extends BaseController
{
    @Autowired
    private ICommonTravelersService commonTravelersService;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private ICommonAddressesService commonAddressesService;
    @Autowired
    private ICommonReimbursementsService commonReimbursementsService;

    @Autowired
    private ICustomerService customerService;

    /**
     * 查询常用旅客信息列表
     */
    //@PreAuthorize(hasPermi = "customer:travelers:list")
    @GetMapping("/list")
    public TableDataInfo list(CommonTravelers commonTravelers)
    {
        startPage();
        List<CommonTravelers> list = commonTravelersService.selectCommonTravelersList(commonTravelers);
        return getDataTable(list);
    }

    /**
     * 导出常用旅客信息列表
     */
    //@PreAuthorize(hasPermi = "customer:travelers:export")
    @Log(title = "常用旅客信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommonTravelers commonTravelers) throws IOException
    {
        List<CommonTravelers> list = commonTravelersService.selectCommonTravelersList(commonTravelers);
        ExcelUtil<CommonTravelers> util = new ExcelUtil<CommonTravelers>(CommonTravelers.class);
        util.exportExcel(response, list, "常用旅客信息数据");
    }

    /**
     * 获取常用旅客信息详细信息
     */
    //@PreAuthorize(hasPermi = "customer:travelers:query")
    @GetMapping(value = "/{primaryKeyId}")
    public AjaxResult getInfo(@PathVariable("commonTrvelersId") Long commonTrvelersId)
    {
        return AjaxResult.success(commonTravelersService.selectCommonTravelersById(commonTrvelersId));
    }

    /**
     * 新增常用旅客信息
     */
    //@PreAuthorize(hasPermi = "customer:travelers:add")
    @Log(title = "常用旅客信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CommonTravelers commonTravelers)
    {
        return toAjax(commonTravelersService.insertCommonTravelers(commonTravelers));
    }

    /**
     * 修改常用旅客信息
     */
    //@PreAuthorize(hasPermi = "customer:travelers:edit")
    @Log(title = "常用旅客信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CommonTravelers commonTravelers)
    {
        return toAjax(commonTravelersService.updateCommonTravelers(commonTravelers));
    }

    /**
     * 修改常用旅客信息（远程调用）
     */
    @Log(title = "常用旅客信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edits")
    public int edits(@RequestBody CommonTravelers commonTravelers)
    {
        return commonTravelersService.updateCommonTravelers(commonTravelers);
    }

    /**
     * 删除常用旅客信息
     */
    //@PreAuthorize(hasPermi = "customer:travelers:remove")
    @Log(title = "常用旅客信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{commonTrvelersIds}")
    public AjaxResult remove(@PathVariable Long[] commonTrvelersIds)
    {
        return toAjax(commonTravelersService.deleteCommonTravelersByIds(commonTrvelersIds));
    }

    /**
     * 新增旅客信息
     * */
//    @SignatureValidation
    @PostMapping("/editCommonlyUsedTraveler")
    public AjaxResult editCommonlyUsedTraveler(HttpServletRequest request, @RequestBody CommonTravelersVo commonTravelersVo) {
        Long customerId;
        try {
            customerId = loginService.getLoginCustomer(request).getCustomerId();
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        commonTravelersVo.setMemberId(customerId);
        int commonTravelersNum = commonTravelersService.saveCommonTravelersByMemberId(commonTravelersVo);
        if (commonTravelersNum > 0){
            return AjaxResult.success(commonTravelersNum);
        }
        else {
            return AjaxResult.error("添加失败");
        }
    }

    /**
     * 旅客列表
     * @param request
     * @return
     */
    @PostMapping("/passenger")
    public AjaxResult passenger(HttpServletRequest request) {
        String token = request.getHeader("token");
        List<PassengerList> passenger = commonTravelersService.passenger(token);
        return AjaxResult.success(passenger);
    }

    /**
     * 获取国家列表
     * */
    @PostMapping("/nationList")
    public AjaxResult nationList(@RequestBody Map<String, Object> map){
        String nationName = null;
        if (map.get("nationName") != null){
            nationName = map.get("nationName").toString();
        }

        NationVo nationVo;
        try {
            nationVo = commonTravelersService.selectNationVo(nationName);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (nationVo != null){
            return AjaxResult.success(nationVo);
        }
        else {
            return AjaxResult.error("获取国家列表失败");
        }
    }

    /**
     * 查询待编辑的常用旅客信息
     * */
    //@SignatureValidation
    @PostMapping("/selectPassengerInformation")
    public AjaxResult selectPassengerInformation(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Long commonTrvelersId = Long.valueOf(map.get("commonTrvelersId").toString());
        Long customerId;
        try {
            customerId = loginService.getLoginCustomer(request).getCustomerId();
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        CommonTravelersVo commonTravelersVo = commonTravelersService.selectPassengerInformation(commonTrvelersId, customerId);
        if (commonTravelersVo != null){
            return AjaxResult.success(commonTravelersVo);
        }
        else {
            return AjaxResult.error("未找到该旅客信息");
        }
    }

    /**
     * 修改常用旅客信息
     * */
    @PostMapping("/modifyPassenger")
    public AjaxResult modifyPassenger(@RequestBody CommonTravelersVo commonTravelersVo){
        int count = 0;
        try {
            count = commonTravelersService.modifyPassenger(commonTravelersVo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        if (count == 1){
            return AjaxResult.success(count);
        }
        else {
            return AjaxResult.error("编辑失败");
        }
    }

    @PostMapping("/queryByCustomerIdCommon")
    public AjaxResult queryByCustomerIdCommon(Long customerId) {
        CommonTravelersDto commonTravelersDto = commonTravelersService.queryByCustomerIdCommon(customerId);
        if (commonTravelersDto != null) {
            return AjaxResult.success(commonTravelersDto);
        } else {
            return AjaxResult.error("查询失败");
        }
    }

    /**
     * 删除常用旅客信息
     * */
    //@SignatureValidation
    @PostMapping("/tombstone")
    public AjaxResult tombstone(HttpServletRequest request, @RequestBody Map<String, Object> map){
        Long commonTrvelersId = Long.valueOf(map.get("commonTrvelersId").toString());
        Long customerId;
        try {
            customerId = loginService.getLoginCustomer(request).getCustomerId();
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        int tombstone;
        try {
            tombstone = commonTravelersService.tombstone(commonTrvelersId, customerId);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (tombstone > 0){
            return AjaxResult.success("删除成功");
        }
        else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 删除常用旅客信息
     * */
    @PostMapping("/delFrequentTraveler")
    public String delFrequentTraveler(@RequestParam("token") String token, @RequestParam("commonTrvelersId") Long commonTrvelersId){
        Long customerId;
        try {
            customerId = loginService.getLoginCustomerByToken(token).getCustomerId();
        } catch (Exception e){
            return e.getMessage();
        }
        if (commonTrvelersId != null && commonTrvelersId > 0){
            int tombstone;
            try {
                tombstone = commonTravelersService.tombstone(commonTrvelersId, customerId);
            } catch (Exception e){
                return e.getMessage();
            }

            if (tombstone > 0){
                return String.valueOf(tombstone);
            }
            else {
                return "0";
            }
        }
        else {
            return "缺少必要参数";
        }
    }

    @PostMapping("/queryPassengerByCustomerId")
    public List<CommonPassenger> queryPassengerByCustomerId(@RequestParam("customerId") Long customerId, @RequestParam("commonTrvelersId") Long commonTrvelersId, @RequestParam("certificateType") String certificateType) {
        List<CommonPassenger> commonPassenger = commonTravelersService.queryPassengerByCustomerId(customerId, commonTrvelersId, certificateType);
        return commonPassenger;
    }

    /**
     * 查询会员全部常用旅客
     * */
    //@SignatureValidation
    @PostMapping("generalInformation")
    public AjaxResult generalInformation(HttpServletRequest request, @RequestBody Map<String, Object> map){
        Long type = Long.valueOf(map.get("type").toString());
        Long memberId;
        try {
            memberId = loginService.getLoginCustomer(request).getCustomerId();
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
        if (type == 1){
            LetterVo letterVo;
            letterVo = commonTravelersService.generalInformation(memberId);
            if (letterVo == null ){
                return AjaxResult.error("数据为空");
            }
            return AjaxResult.success(letterVo);
        }
        else if (type == 2){
            List<CAddressVo> cAddressVoList;
            try {
                cAddressVoList = commonAddressesService.addressList(memberId);
                if (cAddressVoList == null ){
                    return AjaxResult.error("数据为空");
                }
            } catch (Exception e){
                return AjaxResult.error("未查到该会员对应地址信息");
            }
            return AjaxResult.success(cAddressVoList);
        }
        else if (type == 3){
            List<CommonReimbursementsVo> commonReimbursementsVoList;
            String invoiceType = map.get("invoiceType").toString();
            try {
                commonReimbursementsVoList = commonReimbursementsService.selectCommonReimbursements(memberId, invoiceType);
                if (commonReimbursementsVoList == null ){
                    return AjaxResult.error("数据为空");
                }
            } catch (Exception e){
                return AjaxResult.error("未查到该会员对应凭证信息");
            }
            return AjaxResult.success(commonReimbursementsVoList);
        }
        return AjaxResult.error("传入参数错误");
    }

    /**
     * 会员常用旅客信息列表（远程）
     * */
    @PostMapping("/CustomerTravelerList")
    public List<CustomerTraveler> CustomerTravelerList(Long memberId){
        List<CustomerTraveler> customerTravelerList = commonTravelersService.CustomerTravelerList(memberId);
        if (customerTravelerList != null && customerTravelerList.size() > 0){
            return customerTravelerList;
        }
        else {
            return null;
        }
    }

    /**
     * 火车票添加乘车人
     * @param request
     * @param information
     * @return
     */
    //@SignatureValidation
    @PostMapping("/insertCommonTraveler")
    public AjaxResult insertCommonTraveler(HttpServletRequest request, @RequestBody PassengerInformation information) {
        String token = request.getHeader("token");
        int commonTraveler = commonTravelersService.insertCommonTraveler(token, information);
        if (commonTraveler == 1) {
            return AjaxResult.success("添加成功！");
        } else {
            return AjaxResult.error("添加失败，该乘车人已存在！");
        }
    }

    /**
     * 火车票添加乘车人（远程调用）
     * @param token
     * @param information
     * @return
     */
    @PostMapping("/insertCommonTravelers")
    public int insertCommonTravelers(@RequestParam("token") String token, @RequestBody PassengerInformation information) {
        return commonTravelersService.insertCommonTraveler(token, information);
    }

    /**
     * 火车票添加乘车人（CRM远程调用）
     * @param customerId
     * @param information
     * @return
     */
    @PostMapping("/insertCommonTravelersCrm")
    public int insertCommonTravelersCrm(@RequestParam("customerId") Long customerId, @RequestBody PassengerInformation information) {
        return commonTravelersService.insertCommonTravelerCrm(customerId, information);
    }

    /**
     * 火车票-乘车人列表
     * */
    //@SignatureValidation
    @PostMapping("/passengerList")
    public AjaxResult passengerList(HttpServletRequest request, @RequestBody Map<String, Object> map){
        Long memberId;
        String phone;
        try {
            if (map.get("customerId") != null && !map.get("customerId").equals("")){
                Long customerId = Long.valueOf(map.get("customerId").toString());
                memberId = customerService.InquireCustomerById(customerId).getCustomerId();
                phone = customerService.selectCustomerById(customerId).getContractPhoneOne();
            }
            else {
                memberId = loginService.getLoginCustomer(request).getCustomerId();
//                memberId = 24l;
//                phone = "19831144927";
                phone = loginService.getLoginCustomer(request).getContractPhoneOne();
            }
        } catch (Exception e){
            return AjaxResult.expired("登录已过期，请重新登录");
        }

        try {
            if (map.get("customerId") != null && !map.get("customerId").equals("")){
                List<CommonTravelersDtoVo> commonTravelersDtoVos = commonTravelersService.passengerListCrm(memberId, phone);
                if (commonTravelersDtoVos != null && commonTravelersDtoVos.size() > 0){
                    return AjaxResult.success(commonTravelersDtoVos);
                }
                else {
                    return AjaxResult.error("未查到乘车人信息");
                }
            }
            else {
                LetterDto letterDto = commonTravelersService.passengerList(memberId, phone);
                if (letterDto != null && !letterDto.equals("")){
                    return AjaxResult.success(letterDto);
                }
                else {
                    return AjaxResult.error("未查到乘车人信息");
                }
            }


        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("查询异常");
        }
    }

    /**
     * 查询国家列表
     * @return
     */
    @GetMapping("/selectNationList")
    public TableDataInfo selectNationList() {
        startPage();
        List<Nation> nations = commonTravelersService.selectNationList();
        return getDataTable(nations);
    }

    /**
     * 火车票-乘车人详细信息
     * */
    @PostMapping("/passengerDetails")
    public AjaxResult passengerDetails(HttpServletRequest request, @RequestBody Map<String, Object> map){
        Customer loginCustomer;
        String commonTrvelersId;
        try {
            if (map.get("customerId") != null && !map.get("customerId").equals("")){
                Long customerId = Long.valueOf(map.get("customerId").toString());
                loginCustomer = customerService.InquireCustomerById(customerId);
            }
            else {
                loginCustomer = loginService.getLoginCustomer(request);
            }
            commonTrvelersId = map.get("commonTrvelersId").toString();
        } catch (Exception e){
            return AjaxResult.error("参数错误");
        }
        CommonTravelersDetailsVo detailsVo;
        try {
            detailsVo = commonTravelersService.passengerDetails(commonTrvelersId, loginCustomer);
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

        if (detailsVo != null && !detailsVo.equals(null)){
            return AjaxResult.success(detailsVo);
        }
        else {
            return AjaxResult.error("查询失败");
        }
    }

    /**
     * 火车票-修改乘车人信息
     * */
    @PostMapping("/updatepassenger")
    public AjaxResult updatepassenger(@RequestBody Map<String, Object> map){
        String ticketType = null;
        String domesticPhone;
        Long commonTrvelersId;
        try {
            commonTrvelersId = Long.valueOf(map.get("commonTrvelersId").toString());
            domesticPhone = map.get("domesticPhone").toString();
            if (map.get("ticketType") != null && !map.get("ticketType").equals("")){
                ticketType = map.get("ticketType").toString();
            }
        } catch (Exception e){
            return AjaxResult.error("参数错误");
        }
        CommonTravelers commonTravelers = new CommonTravelers();
        commonTravelers.setCommonTrvelersId(commonTrvelersId);
        commonTravelers.setTicketType(ticketType);
        commonTravelers.setDomesticPhone(domesticPhone);

        int count;
        try {
            count = commonTravelersService.updatepassenger(commonTravelers);
            if (count > 0){
                return AjaxResult.success("修改成功");
            }
            else {
                return AjaxResult.error("修改失败");
            }
        } catch (Exception e){
            return AjaxResult.error("修改过程出现异常");
        }
    }

    /**
     * 后端——查询常用旅客信息
     * */
    @PostMapping("/frequentTraveler")
    public AjaxResult backSelectCommonTravelersBack(@RequestBody Map<String, Object> map) {
        if (map.get("customerId") != null && !map.get("customerId").equals("")){
            Long customerId = Long.valueOf(map.get("customerId").toString());
            List<CommonTravelersBack> commonTravelersBackList;
            try {
                commonTravelersBackList = commonTravelersService.backSelectCommonTravelersBack(customerId);
            } catch (Exception e){
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());
            }
            if (commonTravelersBackList != null && commonTravelersBackList.size() > 0){
                return AjaxResult.success(commonTravelersBackList);
            }
            else {
                return AjaxResult.error("该数据为空");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 后端——新增常用旅客
     * */
    @PostMapping("/addPassenger")
    public AjaxResult backInsertCommonTravelersBack(@RequestBody CommonTravelersBack commonTravelersBack){
        Customer customer;
        customer = customerService.InquireCustomerById(commonTravelersBack.customerId);
        if (customer != null){
            if (commonTravelersBack != null){
                Long customerId = customer.getCustomerId();
                int i;
                try {
                    i = commonTravelersService.backInsertCommonTravelersBack(commonTravelersBack, customerId);
                } catch (Exception e){
                    return AjaxResult.error(e.getMessage());
                }
                if (i > 0){
                    return AjaxResult.success("新增成功");
                }
                else {
                    return AjaxResult.error("新增失败");
                }
            }
            else {
                return AjaxResult.error("缺少必要参数");
            }
        }
        else {
            return AjaxResult.error("登陆已过期，请重新登录");
        }
    }

    /**
     * 机票-乘客列表
     * */
    @PostMapping("/fileCommonTravelers")
    public List<CommonTravelers> fileCommonTravelers(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Long customerId;
        if (map.get("customerId") != null && !map.get("customerId").equals("")){
            customerId = Long.valueOf(map.get("customerId").toString());
        }
        else {
            String token = request.getHeader("token");
            customerId = loginService.getLoginCustomerByToken(token).getCustomerId();

        }
        List<CommonTravelers> commonTravelers = commonTravelersService.fileCommonTravelers(customerId);
        if (commonTravelers.size() > 0){
            return commonTravelers;
        }
        else {
            return null;
        }
    }

    /**
     * 后端——修改常用旅客
     * */
    @PostMapping("/backUpdateCommonTravelers")
    public AjaxResult backUpdateCommonTravelers(HttpServletRequest request, @RequestBody CommonTravelersBack commonTravelersBack){
        Customer customer;
        commonTravelersBack.setCommonTrvelersId(new Long(commonTravelersBack.getTrvelersId()));
        if (commonTravelersBack.customerId != null && commonTravelersBack.customerId != 0){
            customer = customerService.InquireCustomerById(commonTravelersBack.customerId);
        }
        else {
            customer = loginService.getLoginCustomer(request);
        }
        if (customer != null){
            int i;
            try {
                i = commonTravelersService.backUpdateCommonTravelers(commonTravelersBack, customer.getCustomerId());
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
            if (i > 0){
                return AjaxResult.success("修改成功");
            }
            else {
                return AjaxResult.success("修改失败");
            }
        }
        else {
            return AjaxResult.error("登录已过期");
        }
    }

    /**
     * 后端——删除常用旅客证件信息
     * */
    @PostMapping("/backDeleteDocuments")
    public AjaxResult backDeletePassengerDocuments(@RequestBody Map<String, Object> map){
        if (map.get("commontrvelersId") != null && !map.get("commontrvelersId").equals("")){
            Long commontrvelersId = Long.valueOf(map.get("commontrvelersId").toString());
            int documents;
            try {
                documents = commonTravelersService.backDeletePassengerDocuments(commontrvelersId);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
            if (documents > 0){
                return AjaxResult.success("删除成功");
            }
            else {
                return AjaxResult.error("删除失败");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 后端——修改常用旅客证件信息
     * */
    @PostMapping("/backUpdateDocuments")
    public AjaxResult backUpdatePassengerDocuments(@RequestBody PassengerDocuments passengerDocuments){
        if (passengerDocuments.getPassengerDocumentsId() != null && passengerDocuments.getPassengerDocumentsId() != 0){
            int documents;
            try {
                documents = commonTravelersService.backUpdatePassengerDocuments(passengerDocuments);
            } catch (Exception e){
                return AjaxResult.error("修改失败");
            }
            if (documents > 0){
                return AjaxResult.success("修改成功");
            }
            else {
                return AjaxResult.error("修改失败");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 后端——查询待修改的旅客证件信息
     * */
    @PostMapping("/backSelectDocumentsById")
    public AjaxResult backSelectDocumentsById(@RequestBody Map<String, Object> map){
        if (map.get("passengerDocumentsId") != null && !map.get("passengerDocumentsId").equals("")){
            Long passengerDocumentsId = Long.valueOf(map.get("passengerDocumentsId").toString());
            CommonTravelersBack commonTravelersBack;
            try {
                commonTravelersBack = commonTravelersService.backSelectDocumentsById(passengerDocumentsId);
            } catch (Exception e){
                return AjaxResult.error(e.getMessage());
            }
            if (commonTravelersBack != null){
                return AjaxResult.success(commonTravelersBack);
            }
            else {
                return AjaxResult.error("未查到数据");
            }
        }
        else {
            return AjaxResult.error("缺少必要参数");
        }
    }

    /**
     * 门票旅客列表
     * */
    @PostMapping("/ticketsTravelerList")
    public AjaxResult ticketsTravelerList(HttpServletRequest request){
        Map<String, List<Map<String, Object>>> stringListMap = commonTravelersService.ticketsTravelerList(request);
        return AjaxResult.success(stringListMap);
    }
}
